package com.zjdiepu.www.hzicbc.biz.impl;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.diepu.www.client.hzicbc.proxy.enums.CertificatesType;
import com.diepu.www.client.hzicbc.proxy.enums.PicIdType;
import com.diepu.www.client.hzicbc.proxy.enums.RelationType;
import com.diepu.www.client.hzicbc.proxy.enums.ReturnCodePrefixType;
import com.diepu.www.client.hzicbc.proxy.request.PublicRequest;
import com.diepu.www.client.hzicbc.proxy.request.applyCredit.ApplyCreditInfo;
import com.diepu.www.client.hzicbc.proxy.request.applyCredit.ApplyCreditRequest;
import com.diepu.www.client.hzicbc.proxy.request.applyCredit.CustomerInfo;
import com.diepu.www.client.hzicbc.proxy.request.common.PicInfo;
import com.diepu.www.client.hzicbc.proxy.request.qryMargin.QryMarginRequest;
import com.diepu.www.client.hzicbc.proxy.response.qryMargin.Account;
import com.diepu.www.client.hzicbc.proxy.response.qryMargin.AccountInfo;
import com.diepu.www.client.proxy.hzicbc.request.CreditResultInfo;
import com.diepu.www.client.proxy.hzicbc.request.CreditResultRequest;
import com.diepu.www.client.proxy.hzicbc.request.CreditResultRequest.CreditApply;
import com.diepu.www.client.proxy.partner.request.own.DiepuIcbcQryMarginRequest;
import com.icbc.api.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.AttachmentLabel;
import com.zjdiepu.www.base.enums.type.AttachmentType;
import com.zjdiepu.www.base.enums.type.CreditPeopleType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.TypeData;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.diepu.biz.IQiniuProxySerive;
import com.zjdiepu.www.diepu.enums.ModeIDTypeDiepu;
import com.zjdiepu.www.diepu.enums.TransferStatusDiepu;
import com.zjdiepu.www.enums.TransferModeID;
import com.zjdiepu.www.hzicbc.biz.HzicbcBizApiService;
import com.zjdiepu.www.proxy.biz.impl.BaseProxyService;
import com.zjdiepu.www.proxy.biz.own.HzBiz;
import com.zjdiepu.www.proxy.biz.own.HzGhBiz;
import com.zjdiepu.www.proxy.biz.own.LogsBiz;
import com.zjdiepu.www.proxy.biz.transfer.INewTransaction;
import com.zjdiepu.www.proxy.dao.transfer.TransferZxCreditQueryMapper;
import com.zjdiepu.www.proxy.dao.transfer.TransferZxQueryCreditApplySubMapper;
import com.zjdiepu.www.proxy.model.dto.own.SysUserProxy;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferLogs;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferLogsSub;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferOtherAttachments;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwOrdernoBank;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferZxCreditQuery;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferZxQueryCreditApply;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferZxQueryCreditApplySub;
import com.zjdiepu.www.proxy.model.ext.transfer.TransferZxQueryCreditApplySubExt;
import com.zjdiepu.www.service.partner.IcbcApiService;

@Service
public class HzicbcBizApiServiceImpl extends BaseProxyService implements HzicbcBizApiService{
	private final Logger logger = LoggerFactory.getLogger(getClass());

	private final int diepu2MinuteTask = 0;
	
	private final int diepu5MinuteTask = 2;
	
	private final int diepu10MinuteTask = 5;
	
	@Autowired
	private INewTransaction newTransaction;
	
	@Autowired
	private HzBiz hzBiz;
	
	@Autowired
	private LogsBiz logsBiz;
	
	@Autowired
	private TransferZxQueryCreditApplySubMapper transferZxQueryCreditApplySubMapper;
	
	@Autowired
	private IcbcApiService icbcApiService;
	
	@Autowired
	private TransferZxCreditQueryMapper transferZxCreditQueryMapper;
	
	@Autowired
	private HzGhBiz hzGhBiz;
	
	@Autowired
	private IQiniuProxySerive qiniuProxySerive;
	
	@Override
	public boolean diepuIcbcApplyQuery(SysUserProxy sysUserProxy,String orderno,String zoneno,String dataId,String modeId) 
	{
		String retcode = "";
		ApiResponse ar = null;
		boolean responseBoolen = false;
		
		if(StringUtils.isBlank(dataId) || StringUtils.isBlank(modeId)) {
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setDataId(dataId);
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
			transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
			transferLogs.setDescribeEvent(ResultFlagType.PARAM_EMPTY.getValue());
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError(ResultFlagType.PARAM_EMPTY.getValue());
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),ResultFlagType.PARAM_EMPTY.getValue());
		}
		
		//查询征信子表
		TransferZxQueryCreditApplySub zxQueryCreditApplySub = transferZxQueryCreditApplySubMapper.selectByPrimaryKey(dataId);
		if(null == zxQueryCreditApplySub) {
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setDataId(dataId);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
			transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
			transferLogs.setDescribeEvent("transferZxQueryCreditApplySubMapper selectByPrimaryKey is null");
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError("transferZxQueryCreditApplySubMapper selectByPrimaryKey is null");
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),"transferZxQueryCreditApplySubMapper selectByPrimaryKey is null");
		}
		
		//判断是否为主借人
		String creditPeopleType = zxQueryCreditApplySub.getCreditPeopleType();
		if(StringUtils.isBlank(creditPeopleType)) {
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setDataId(dataId);
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
			transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
			transferLogs.setDescribeEvent("creditPeopleType is null");
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError("creditPeopleType is null");
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),"creditPeopleType is null");
		}
//		2018-02-02
		String sqlXmls = "select count(t.id) count from transfer_other_attachments t where t.mode_id = '"+modeId+"' and t.dataid = '"+zxQueryCreditApplySub.getQueryCreditApplyId()+"' and t.sub_dataid = '"+dataId+"' and t.local_file_path <> '' and t.local_file_path is not null and t.dp_status = 1 and t.type_data = 1";
		
		//查询附件是否完整
		int count = hzBiz.countSqlXmls(sqlXmls);
		if(count < 1) {
			hzBiz.loggerInfo("附件不完整");
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setDataId(zxQueryCreditApplySub.getQueryCreditApplyId());
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
			transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
			transferLogs.setDescribeEvent("附件不完整");
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			
			//增加一个2分钟之后【同步附件】的定时任务   
			newTransaction.saveHqfjlbTaskWith2Minutes(orderno, zxQueryCreditApplySub.getQueryCreditApplyId(),diepu2MinuteTask);
			//增加一个5分钟之后【下载附件】的定时任务   
			newTransaction.xzfjTaskWith5Minutes(orderno, zxQueryCreditApplySub.getQueryCreditApplyId(),diepu5MinuteTask);
			//10分钟后【向工行申请查征信】的定时任务  
			newTransaction.sqczxTaskWith10Minute(orderno, zxQueryCreditApplySub.getQueryCreditApplyId(),diepu10MinuteTask);
		}
		
		if(count > 0) {
			//主借人对象
			TransferZxQueryCreditApply zxQueryCreditApply = null;
			if(CreditPeopleType.PEI_OU.getCode().equals(creditPeopleType) || CreditPeopleType.DAN_BAO_REN.getCode().equals(creditPeopleType)) {
				zxQueryCreditApply = transferZxQueryCreditApplyMapper.selectByPrimaryKey(zxQueryCreditApplySub.getQueryCreditApplyId());
				if(null == zxQueryCreditApply) {
					TransferLogs transferLogs = new TransferLogs();
					transferLogs.setBankOrderNo(orderno);
					transferLogs.setDataId(zxQueryCreditApplySub.getQueryCreditApplyId());
					transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
					transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
					transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
					transferLogs.setDescribeEvent("transferZxQueryCreditApplySubMapper selectRefined is null");
					logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
					hzBiz.loggerError("transferZxQueryCreditApplyMapper selectRefined is null");
					throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),"transferZxQueryCreditApplyMapper selectRefined is null");
				}
			}
			
			//主申请人名称
			String mastername = "";
			String relation = "";
			if(CreditPeopleType.PEI_OU.getCode().equals(creditPeopleType)) { //配偶
				mastername = zxQueryCreditApply.getCustomerName();
				relation = RelationType.PEI_OU.getCode();
			} else if(CreditPeopleType.DAN_BAO_REN.getCode().equals(creditPeopleType)) { //担保人
				mastername = zxQueryCreditApply.getCustomerName();
				relation = RelationType.FAN_DAN_BAO.getCode();
			} else if(CreditPeopleType.ZHU_JIE_REN.getCode().equals(creditPeopleType)) { //主借人
				mastername = zxQueryCreditApplySub.getCusName();
				relation = RelationType.BEN_REN.getCode();
			}
			
			ApplyCreditRequest request = new ApplyCreditRequest();
			PublicRequest pub = preparedPub(orderno, zoneno);
			request.setPub(pub);
			
			ApplyCreditInfo req = new ApplyCreditInfo();
			
			CustomerInfo customerInfo = new CustomerInfo();
			customerInfo.setMastername(mastername);
			customerInfo.setCustname(zxQueryCreditApplySub.getCusName());
			customerInfo.setIdtype(CertificatesType.CERT_SFZ.getCode());
			customerInfo.setIdno(zxQueryCreditApplySub.getCusNo());
			customerInfo.setRelation(relation);
			req.setCustomer(customerInfo);
			
//			@2018-03-07改造重构附件文件判断和组装请求参数 ===================开始================
//			准备临时句柄（附件参数，文档对象，同步附件列表，下载附件，附件记录）
			List<PicInfo> pics = new ArrayList<PicInfo>();
			
			TransferOtherAttachments transferOtherAttachmentsParam = new TransferOtherAttachments();
			transferOtherAttachmentsParam.setDataid(zxQueryCreditApplySub.getQueryCreditApplyId());
			transferOtherAttachmentsParam.setSubDataid(dataId);
			transferOtherAttachmentsParam.setModeId(modeId);
			transferOtherAttachmentsParam.setDpStatus(DpStatus.NORMAL.getCode());
			PicInfo picInfo = null;
			boolean hqfjlb = false;
			boolean xzfj = false;
			try {
				TransferOtherAttachments transferOtherAttachments = null;
				if(CreditPeopleType.ZHU_JIE_REN.getCode().equals(creditPeopleType)) {//主借人
					transferOtherAttachmentsParam.setAttachmentType(AttachmentType.WORD.getCode());
					transferOtherAttachmentsParam.setFileLabel(AttachmentLabel.SHOU_QUAN_ZHENG_MING.getCode());
					transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					if(null == transferOtherAttachments) {
						transferOtherAttachmentsParam.setSubDataid(zxQueryCreditApplySub.getQueryCreditApplyId());
						transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					}
					if(null == transferOtherAttachments) {
						hqfjlb = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "主借人【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】缺失查征信授权Word");
					}
					if(!hzBiz.checkCompleted(transferOtherAttachments)) {
						xzfj = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "请下载同步主借人【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】查征信授权Word");
					}
					
					transferOtherAttachments.setPicid(PicIdType.ZX_DOC.getCode());
					picInfo = getPicInfo(transferOtherAttachments);
					picInfo.setPicnote("【征信】客户征信查询授权书+身份证正反面.doc");
					pics.add(picInfo);
					
					transferOtherAttachmentsParam.setAttachmentType(AttachmentType.IMAGE.getCode());
					transferOtherAttachmentsParam.setFileLabel(AttachmentLabel.ZHUJIEREN_ZHENG_XIN_QIANZIZHAO.getCode());
					transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					if(null == transferOtherAttachments) {
						hqfjlb = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "主借人【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】缺失申请书签字照");
					}
					if(!hzBiz.checkCompleted(transferOtherAttachments)) {
						xzfj = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "请下载同步主借人【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】申请书签字照");
					}
					transferOtherAttachments.setPicid(PicIdType.ZX_SQQZZO.getCode());
					picInfo = getPicInfo(transferOtherAttachments);
					picInfo.setPicnote("【征信】授权书签字照片");
					pics.add(picInfo);
				} else if(CreditPeopleType.PEI_OU.getCode().equals(creditPeopleType)) { //配偶
					transferOtherAttachmentsParam.setAttachmentType(AttachmentType.WORD.getCode());
					transferOtherAttachmentsParam.setFileLabel(AttachmentLabel.SHOU_QUAN_ZHENG_MING.getCode());
					transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					if(null == transferOtherAttachments) {
						hqfjlb = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "配偶【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】缺失查征信授权Word");
					}
					if(!hzBiz.checkCompleted(transferOtherAttachments)) {
						xzfj = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "请下载同步配偶【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】查征信授权Word");
					}
					transferOtherAttachments.setPicid(PicIdType.ZX_DOC.getCode());
					picInfo = getPicInfo(transferOtherAttachments);
					picInfo.setPicnote("【征信】客户征信查询授权书+身份证正反面.doc");
					pics.add(picInfo);
					
					transferOtherAttachmentsParam.setAttachmentType(AttachmentType.IMAGE.getCode());
					transferOtherAttachmentsParam.setFileLabel(AttachmentLabel.PEIOU_ZHENG_XIN_QIANZIZHAO.getCode());
					transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					if(null == transferOtherAttachments) {
						hqfjlb = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "配偶【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】缺失申请书签字照");
					}
					if(!hzBiz.checkCompleted(transferOtherAttachments)) {
						xzfj = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "请下载同步配偶【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】申请书签字照");
					}
					transferOtherAttachments.setPicid(PicIdType.ZX_SQQZZO.getCode());
					picInfo = getPicInfo(transferOtherAttachments);
					picInfo.setPicnote("【征信】授权书签字照片");
					pics.add(picInfo);
				} else if(CreditPeopleType.DAN_BAO_REN.getCode().equals(creditPeopleType)) { //担保人
					transferOtherAttachmentsParam.setAttachmentType(AttachmentType.WORD.getCode());
					transferOtherAttachmentsParam.setFileLabel(AttachmentLabel.SHOU_QUAN_ZHENG_MING.getCode());
					transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					if(null == transferOtherAttachments) {
						hqfjlb = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "担保人【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】缺失查征信授权Word");
					}
					if(!hzBiz.checkCompleted(transferOtherAttachments)) {
						xzfj = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "请下载同步配偶【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】查征信授权Word");
					}
					transferOtherAttachments.setPicid(PicIdType.ZX_DOC.getCode());
					picInfo = getPicInfo(transferOtherAttachments);
					picInfo.setPicnote("【征信】客户征信查询授权书+身份证正反面.doc");
					pics.add(picInfo);
					
					transferOtherAttachmentsParam.setAttachmentType(AttachmentType.IMAGE.getCode());
					transferOtherAttachmentsParam.setFileLabel(AttachmentLabel.DANBAOREN1_ZHENG_XIN_QIANZIZHAO.getCode());
					transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					if(null == transferOtherAttachments) {
						transferOtherAttachmentsParam.setAttachmentType(AttachmentType.IMAGE.getCode());
						transferOtherAttachmentsParam.setFileLabel(AttachmentLabel.DANBAOREN2_ZHENG_XIN_QIANZIZHAO.getCode());
						transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					}
					
					if(null == transferOtherAttachments) {
						transferOtherAttachmentsParam.setAttachmentType(AttachmentType.IMAGE.getCode());
						transferOtherAttachmentsParam.setFileLabel(AttachmentLabel.DANBAOREN3_ZHENG_XIN_QIANZIZHAO.getCode());
						transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					}
					
					if(null == transferOtherAttachments) {
						transferOtherAttachmentsParam.setAttachmentType(AttachmentType.IMAGE.getCode());
						transferOtherAttachmentsParam.setFileLabel(AttachmentLabel.DANBAOREN4_ZHENG_XIN_QIANZIZHAO.getCode());
						transferOtherAttachments = transferOtherAttachmentsMapper.selectRefined(transferOtherAttachmentsParam);
					}
					if(null == transferOtherAttachments) {
						hqfjlb = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "担保人【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】缺失申请书签字照");
					}
					if(!hzBiz.checkCompleted(transferOtherAttachments)) {
						xzfj = true;
						throw new BaseException(ResultFlagType.MISSING.getCode(), "请下载同步担保人【" + zxQueryCreditApplySub.getCusName() + "(" +zxQueryCreditApplySub.getCusNo() + ")】申请书签字照");
					}
					transferOtherAttachments.setPicid(PicIdType.ZX_SQQZZO.getCode());
					picInfo = getPicInfo(transferOtherAttachments);
					picInfo.setPicnote("【征信】授权书签字照片");
					pics.add(picInfo);
				} else {
					//角色错误，不会出现
				}
			} finally {
				if(hqfjlb) {
					//写一个时间为2分钟（可配）只有的 从主程序获取附件列表 的定时任务
					newTransaction.saveHqfjlbTaskWith2Minutes(orderno, zxQueryCreditApplySub.getQueryCreditApplyId(), diepu2MinuteTask);
				}
				if(hqfjlb || xzfj) {
					//写一个时间为5分钟（可配）之后的下载附件定时任务
					newTransaction.xzfjTaskWith5Minutes(orderno, zxQueryCreditApplySub.getQueryCreditApplyId(),diepu5MinuteTask );
//					//写一个时间为10分钟（可配）之后的向工行申请查征信定时任务
					newTransaction.sqczxTaskWith10Minute(orderno, zxQueryCreditApplySub.getQueryCreditApplyId(),diepu10MinuteTask);
					
					TransferLogs transferLogs = new TransferLogs();
					transferLogs.setBankOrderNo(orderno);
					transferLogs.setDataId(zxQueryCreditApplySub.getQueryCreditApplyId());
					transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
					transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
					transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
					transferLogs.setBankOrderNo(zxQueryCreditApplySub.getBankOrderNo());
					transferLogs.setDescribeEvent("附件检查不通过，【附件记录不存在】或【附件没有下载同步】");
					logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
				}
			}
//			@2018-03-07改造重构附件文件判断和组装请求参数 ===================结束================
			req.setPics(pics);
			request.setReq(req);
			String describeEvent = null;
			boolean saveLog = false;
			try {
				try {
					ar = hzicbcService.applyCredit(request, hzicbcConfig.getPlatno());
					retcode = hzBiz.retcode(ar);
					
//					@update 2018-02-27 如果申请征信时，工行返回 2*****，把征信结果设置为 禁入，将retmsg 字段的内容作为 征信结果备注（credit_result_mark）返回给主程序（调用主程序的【接口征信结果反馈】）；
					if(StringUtils.isNotBlank(retcode) && retcode.startsWith(ReturnCodePrefixType.FAIL_WDYMXQDWJ.getCode()) 
							&& !ReturnCodePrefixType.FAIL_ZXYCZ_1.getCode().equals(retcode) && !ReturnCodePrefixType.FAIL_ZXYCZ_2.getCode().equals(retcode)
							&& !ReturnCodePrefixType.FAIL_ZXYCZ_3.getCode().equals(retcode)) {
//						TODO 反馈结果到主程序
						String retmsg = hzBiz.retmsg(ar);
						CreditResultRequest creditResultRequest = new CreditResultRequest();
						
						PublicRequest publicRequest = new PublicRequest();
						publicRequest.setOrderno(orderno);
						creditResultRequest.setPub(publicRequest);
						
						CreditResultInfo creditResultInfo = new CreditResultInfo();
						creditResultInfo.setResult("003");
						creditResultInfo.setRelation(relation);
						creditResultInfo.setNote(retmsg);
						creditResultInfo.setCustname(zxQueryCreditApplySub.getCusName());
						creditResultInfo.setIdno(zxQueryCreditApplySub.getCusNo());
						
						creditResultInfo.setLoanCrdt("0");
						creditResultInfo.setCardCrdt("0");
						creditResultInfo.setLeftAmount("0");
						creditResultInfo.setLeftNum("0");
						creditResultRequest.setReq(creditResultInfo);
						
						List<CreditApply> creditApplies = CollectionInitUtil.emptyList();
						CreditApply creditApply = creditResultRequest.newCreditApply();
						creditApply.setQueryCreditApplyId(zxQueryCreditApplySub.getQueryCreditApplyId());
						creditApply.setQueryCreditApplySubId(zxQueryCreditApplySub.getId());
						creditApplies.add(creditApply);
						
						creditResultRequest.creditApplies = creditApplies;
						
						boolean creditResult = icbcApiService.creditResult(creditResultRequest);
						if(!creditResult) {
							logger.error("征信申请返回2***编码，反馈到主程序失败.");
							describeEvent = "征信申请返回2***编码，反馈到主程序失败";
							saveLog = true;
						}
					}
				} catch (Exception e)  {
					logger.error("申请查询征信发生异常.", e);
					describeEvent = "申请查询征信发生异常";
					saveLog = true;
					
					//如果重发次数小于10，写一条10分钟之后的【向工行申请开卡】定时任务，重发次数+1
					newTransaction.sqczxTaskWith10Minute(zxQueryCreditApplySub.getBankOrderNo(), zxQueryCreditApplySub.getQueryCreditApplyId(), 10);
				}
				
				//如果返回成功，将zx_征信查询结果表_杭州工行 和zx_征信查询结果表 的征信查询状态修改为 正在查询（30）
				//如果申请返回代码是000000，将transfer_handle_status 更改为 300（发送成功）；否则将transfer_handle_status更改为 9100(发送失败)；如果重发次数小于10，写一条10分钟之后的【向工行申请开卡】定时任务，重发次数+1；
				TransferZxCreditQuery transferZxCreditQuery = new TransferZxCreditQuery();
				transferZxCreditQuery.setQueryCreditApplySubId(dataId);
				transferZxCreditQuery.setDpStatus(1);
				transferZxCreditQuery.setTypeData(3);
				transferZxCreditQuery = transferZxCreditQueryMapper.selectRefined(transferZxCreditQuery);
				if(null == transferZxCreditQuery) {
					logger.error("征信结果记录丢失.QueryCreditApplySubId : {}.", dataId);
					describeEvent = "征信申请成功，后续处理，征信结果记录丢失";
					saveLog = true;
					throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),"transferZxCreditQueryMapper selectRefined is null");
				}
				
				if(retcode.equals("00000")) {
					responseBoolen = true;
					transferZxCreditQuery.setCreditQueryStatus(30);
					transferZxCreditQuery.setTransferHandleStatus(300);
					count = transferZxCreditQueryMapper.updateByPrimaryKeySelective(transferZxCreditQuery);
				} else if(retcode.equals("22001") || retcode.equals("22002") || retcode.equals("22003")) {
					responseBoolen = true;
					logger.info("订单已经存在.");
					describeEvent = "订单已经存在";
					saveLog = true;
				} else if(retcode.equals("22091")) {
					responseBoolen = true;
					logger.info("全省未结清超过3笔");
					describeEvent = "全省未结清超过3笔";
					saveLog = true;
				} 
				 else if(retcode.equals("22092")) {
						responseBoolen = true;
						logger.info("该地区有未结清记录超过3笔");
						describeEvent = "该地区有未结清记录超过3笔";
						saveLog = true;
					} 
				 else if(retcode.equals("22093")) {
						responseBoolen = true;
						logger.info("该客户有不良记录");
						describeEvent = "该客户有不良记录";
						saveLog = true;
					} 
				 else if(retcode.equals("22094")) {
						responseBoolen = true;
						logger.info("该客户为灰名单客户");
						describeEvent = "该客户为灰名单客户";
						saveLog = true;
					} 
				else {
					transferZxCreditQuery.setTransferHandleStatus(9100);
					count = transferZxCreditQueryMapper.updateByPrimaryKeySelective(transferZxCreditQuery);
					
					//如果重发次数小于10，写一条10分钟之后的【向工行申请开卡】定时任务，重发次数+1
					newTransaction.sqczxTaskWith10Minute(orderno, zxQueryCreditApplySub.getQueryCreditApplyId(), 10);
				}
			} finally {
				if(saveLog) {
					TransferLogs transferLogs = new TransferLogs();
					transferLogs.setDataId(zxQueryCreditApplySub.getQueryCreditApplyId());
					transferLogs.setBankOrderNo(zxQueryCreditApplySub.getBankOrderNo());
					transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
					transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
					transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
					transferLogs.setDescribeEvent(describeEvent);
					TransferLogsSub transferLogsSub = new TransferLogsSub();
					transferLogsSub.setRequestMessageEvent(JSON.toJSONString(request));
					transferLogsSub.setResponseMessageEvent(JSON.toJSONString(ar));
					logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
				}
			}
		}
		return responseBoolen;
	}


	@Override
	public boolean diepuIcbcQryMargin(SysUserProxy sysUserProxy, String orderno,String zoneno) 
	{
		boolean responseBoolen = false;
		String retcode = "";
		if(null == sysUserProxy)
		{
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.CXFXZBJYE.getCode());
			transferLogs.setTransferModeName(TransferModeID.CXFXZBJYE.getValue());
			transferLogs.setDescribeEvent(ResultFlagType.LOGIN_TIMEOUT.getValue());
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError(ResultFlagType.LOGIN_TIMEOUT.getValue());
			throw new BaseException(ResultFlagType.LOGIN_TIMEOUT.getCode().toString(),ResultFlagType.LOGIN_TIMEOUT.getValue());
		}
		
		String userId = sysUserProxy.getUserId();
		String loginName = sysUserProxy.getLoginName();
		if(StringUtils.isBlank(userId) || StringUtils.isBlank(loginName))
		{
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.CXFXZBJYE.getCode());
			transferLogs.setTransferModeName(TransferModeID.CXFXZBJYE.getValue());
			transferLogs.setDescribeEvent(ResultFlagType.LOGIN_TIMEOUT.getValue());
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError(ResultFlagType.LOGIN_TIMEOUT.getValue());
			throw new BaseException(ResultFlagType.LOGIN_TIMEOUT.getCode().toString(),ResultFlagType.LOGIN_TIMEOUT.getValue());
		}
		
		if(StringUtils.isBlank(orderno) || StringUtils.isBlank(zoneno))
		{
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.CXFXZBJYE.getCode());
			transferLogs.setTransferModeName(TransferModeID.CXFXZBJYE.getValue());
			transferLogs.setDescribeEvent(ResultFlagType.PARAM_EMPTY.getValue());
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError(ResultFlagType.PARAM_EMPTY.getValue());
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),ResultFlagType.PARAM_EMPTY.getValue());
		}
		QryMarginRequest request = new QryMarginRequest();
		PublicRequest pub = preparedPub(orderno, zoneno);
		request.setPub(pub);
		
		AccountInfo accountInfo = null;
	    try 
	    {
			accountInfo = hzicbcService.qryMargin(request, hzicbcConfig.getPlatno());
			retcode = hzBiz.retcode(accountInfo);
			if(retcode.equals("00000"))
			{
				responseBoolen = true;
			}
		} 
	    catch (Exception e) 
	    {
	    	TransferLogs transferLogs = new TransferLogs();
	    	transferLogs.setBankOrderNo(orderno);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.CXFXZBJYE.getCode());
			transferLogs.setTransferModeName(TransferModeID.CXFXZBJYE.getValue());
			transferLogs.setDescribeEvent(e.getMessage()+"-"+TransferModeID.CXFXZBJYE.getValue());
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError(e.getMessage()+"-"+TransferModeID.CXFXZBJYE.getValue());
		}
	    
	    if(null == accountInfo)
		{
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.CXFXZBJYE.getCode());
			transferLogs.setTransferModeName(TransferModeID.CXFXZBJYE.getValue());
			transferLogs.setDescribeEvent("accountInfo is null");
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError("accountInfo is null");
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),"accountInfo is null");
		}
		
		//对应工行的【风险准备金余额查询接口】
		//如果工行接口返回码为5个0，那么调用主程序的【更新风险准备金余额】接口。
		//写一个一天后的【向工行查询风险准备金余额】的定时任务；
		
		DiepuIcbcQryMarginRequest diepuIcbcQryMarginRequest = new DiepuIcbcQryMarginRequest();
		diepuIcbcQryMarginRequest.setUserId(userId);
		diepuIcbcQryMarginRequest.setLoginName(loginName);
		diepuIcbcQryMarginRequest.setTotalbal(accountInfo.getTotalbal());
		
		//循环值
		List<Account> accounts = accountInfo.getAccounts();
		if(null == accounts || accounts.size() == 0)
		{
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.CXFXZBJYE.getCode());
			transferLogs.setTransferModeName(TransferModeID.CXFXZBJYE.getValue());
			transferLogs.setDescribeEvent("List<Account> is null");
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError("List<Account> is null");
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),"List<Account> is null");
		}
		
		for(int i=0;i<accounts.size();i++)
		{
			diepuIcbcQryMarginRequest.setAccount(diepuIcbcQryMarginRequest.newAccount());
			BeanUtils.copyProperties(accounts.get(i), diepuIcbcQryMarginRequest.getAccount());
			diepuIcbcQryMarginRequest.getAccounts().add(diepuIcbcQryMarginRequest.getAccount());
		}
		
		try 
		{
			//调用更新风险准备金
			boolean b = icbcApiService.diepuIcbcQryMargin(diepuIcbcQryMarginRequest);
			if(!b)
			{
				
				TransferLogs transferLogs = new TransferLogs();
				transferLogs.setBankOrderNo(orderno);
				transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
				transferLogs.setTransferModeId(TransferModeID.CXFXZBJYE.getCode());
				transferLogs.setTransferModeName(TransferModeID.CXFXZBJYE.getValue());
				transferLogs.setDescribeEvent("IcbcApiService diepuIcbcQryMargin false");
				logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
				logger.error("999", "查询风险准备金异常");
			}
		} 
		catch (Exception e) 
		{
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setBankOrderNo(orderno);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.CXFXZBJYE.getCode());
			transferLogs.setTransferModeName(TransferModeID.CXFXZBJYE.getValue());
			transferLogs.setDescribeEvent(e.getMessage()+"-"+TransferModeID.CXFXZBJYE.getValue());
			logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
			hzBiz.loggerError(e.getMessage()+"-"+TransferModeID.CXFXZBJYE.getValue());
		}
		
		
		//对应工行的【风险准备金余额查询接口】
		//如果工行接口返回码为5个0，那么调用主程序的【更新风险准备金余额】接口。
		//写一个一天后的【向工行查询风险准备金余额】的定时任务；

		//定时任务：
		//Modeid：M_tranfer_cxfxzbjye
		//Dataid：不需要
		//调用【向工行查询风险准备金余额】方法
		
		//调用张老师的 自动执行任务
		newTransaction.cxfxzbjyeTaskWith24Hours(orderno, orderno,24);
		
		TransferLogs transferLogs = new TransferLogs();
		transferLogs.setBankOrderNo(orderno);
		transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
		transferLogs.setTransferModeId(TransferModeID.CXFXZBJYE.getCode());
		transferLogs.setTransferModeName(TransferModeID.CXFXZBJYE.getValue());
		transferLogs.setStatusEvent(Integer.valueOf(TransferStatusDiepu.STATUSEVENT1.getCode()));
		transferLogs.setDescribeEvent("{current module execution success} ... 风险准备金余额查询接口");
		TransferLogsSub transferLogsSub = new TransferLogsSub();
		if(null != request)
		{
			transferLogsSub.setRequestMessageEvent(JSON.toJSONString(request));
		}
		transferLogsSub.setRequestMessageEventEncode(TransferModeID.CXFXZBJYE.getCode());
		if(null != accountInfo)
		{
			transferLogsSub.setResponseMessageEvent(JSON.toJSONString(accountInfo));
		}
		logsBiz.diepuLogs(sysUserProxy, transferLogs, transferLogsSub);
		hzBiz.loggerInfo("{current module execution success} ... 风险准备金余额查询接口");
		return responseBoolen;
	}


	@Override
	public boolean creditTask(String orderno,String datasId,String modeId) throws Exception 
	{
		boolean flag = false;
		TransferZxQueryCreditApplySubExt transferZxQueryCreditApplySubExt = new TransferZxQueryCreditApplySubExt();
		transferZxQueryCreditApplySubExt.setBaseWhere();
		transferZxQueryCreditApplySubExt.withOutPage();
		transferZxQueryCreditApplySubExt.setQueryCreditApplyId(datasId);
		transferZxQueryCreditApplySubExt.setTypeData(TypeData.HZICBC.getCode());
		transferZxQueryCreditApplySubExt.setDpStatus(DpStatus.NORMAL.getCode());
		transferZxQueryCreditApplySubExt.setStatusAttachments("10");
		List<TransferZxQueryCreditApplySub> result = transferZxQueryCreditApplySubMapper.selectByExt(transferZxQueryCreditApplySubExt);
		if(null != result && result.size() > 0)
		{
			SysUserProxy sysUserProxy = new SysUserProxy();
			sysUserProxy.setUserId(SystemConsts.DEFAULT_ID);
			sysUserProxy.setLoginName(TransferModeID.SQCZX.getValue());
			for(int i=0;i<result.size();i++)
			{
				TransferYwOrdernoBank transferYwOrdernoBank = new TransferYwOrdernoBank();
				transferYwOrdernoBank.setQueryCreditApplyId(datasId);
				transferYwOrdernoBank.setOrdeRno(orderno);
				transferYwOrdernoBank.setDpStatus(1);
				transferYwOrdernoBank.setTypeData(3);
				transferYwOrdernoBank = transferYwOrdernoBankMapper.selectRefined(transferYwOrdernoBank);
				if(null == transferYwOrdernoBank)
				{
					TransferLogs transferLogs = new TransferLogs();
					transferLogs.setDataId(datasId);
					transferLogs.setBankOrderNo(orderno);
					transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
					transferLogs.setTransferModeId(TransferModeID.JSCZXSQ.getCode());
					transferLogs.setTransferModeName(TransferModeID.JSCZXSQ.getValue());
					transferLogs.setDescribeEvent("transferYwOrdernoBank is null");
					logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
					throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),"transferYwOrdernoBank is null");
				}
				
				flag = diepuIcbcApplyQuery(sysUserProxy, result.get(i).getBankOrderNo(),transferYwOrdernoBank.getAreaId(), result.get(i).getId(), "M_zxcx");
//				if(!flag)
//				{
//					TransferLogs transferLogs = new TransferLogs();
//					transferLogs.setBankOrderNo(orderno);
//					transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
//					transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
//					transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
//					transferLogs.setDescribeEvent("申请查征信出错");
//					logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
//					hzBiz.loggerError(TransferModeID.SQCZX.getValue());
//					throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),"diepuIcbcApplyQuery error");
//				}
				if(flag)// 只有发送成功才需要更新数据，pan
				{
					result.get(i).setStatusAttachments("20");
					int count = transferZxQueryCreditApplySubMapper.updateByPrimaryKeySelective(result.get(i));
					if(count < 1)
					{
						TransferLogs transferLogs = new TransferLogs();
						transferLogs.setBankOrderNo(orderno);
						transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
						transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
						transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
						transferLogs.setDescribeEvent("申请查征信出错");
						logsBiz.diepuLogs(sysUserProxy, transferLogs, null);
						hzBiz.loggerError(TransferModeID.SQCZX.getValue());
						throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),"transferZxQueryCreditApplySubMapper updateByPrimaryKeySelective error");
					}
				}
			}
		}
		return flag;
	}
}
